import Util from '../../utils/util.js';
import {getGoodsDetail} from "../../api/product";
import {getShopDetail} from "../../api/shop";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {

    skuDialog: false,
    cartDialog: false,

    skus: [],
    checkSkus: [],
    checkSkusTxt: "",

    totalPrice: 0,
    total_price: 0,
    amount: 0,

    buyActive: false,  //购买按钮
    showSkuCartBtn: false, //规格购买按钮显示
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    this.setData(options)

    if (Util.isEmpty(this.data.id)) {
      return app.Tips({title: "参数错误"})
    }

    Util.chekWxLogin().then(res => {
      that.setData({
        userInfo: res.userInfo,
        current_menu: Util.getStorageInfo("current_menu"),
      })

      if (!Util.isEmpty(that.data.current_menu)) {
        this.setData({
          shop_id: that.data.current_menu.shop_id || "",
        })
        const cartList = Util.getCartList(),
          cartKey = this.getCartKey();
        this.setData({
          cartKey: cartKey
        })

        if (!Util.isEmpty(cartList) && !Util.isEmpty(cartList[cartKey])) {
          that.setData({
            cartList: cartList[cartKey] || []
          })
        }

        getShopDetail(that.data.shop_id).then(res => {
          that.setData({
            shop: res.data
          })
        }).then(() => {
          that.cartStat();
        }).catch(errmsg => {
          Util.Tips({title: errmsg})
        }).finally(() => {
          wx.hideLoading()
        })

      }
    }).then(() => {
      wx.showLoading({title: "正在加载..."})
      getGoodsDetail(that.data.id)
        .then(res => {
          that.setData(res.data)
        }).then(() => {
        that._initSkuData();
      })
        .catch(errmsg => {
          Util.Tips({title: errmsg}, {tab: 3})
        })
        .finally(() => {
          that.onLoadTabbar();
          wx.hideLoading();
        })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  goCheckout(e) { //去结算
    const that = this,
      cartTotal = this.data.cartTotal,
      shop = this.data.shop;

    if (Util.isEmpty(this.data.cartList)) {
      Util.Tips({title: "至少选择一个上商品", hideMask: true})
      return;
    }

    if (Util.isEmpty(cartTotal))
      return Util.Tips({title: "请选择商品", hideMask: true});

    if (cartTotal.total_price < cartTotal.shop_min_money) {
      return Util.Tips({title: "起送价格最低" + cartTotal.shop_min_money})
    }

    wx.setStorageSync('cartKey', this.data.cartKey);
    wx.navigateTo({
      url: "../cart/checkout"
    })
  },

  //关闭规格
  closeSku(e) {
    this.setData({
      skuDialog: false,
      skus: [],
      checkSkus: [],
      checkSkuTxt: '',
      totalPrice: 0,
    })
  },

  //规格-添加到购物车
  confirmAddCart(e) {
    const that = this;
    let cartKey = this.data.current_cartKey,
      currentGoods = this.data.currentGoods,
      cartList = {};

    let carts = Util.getCartList();
    cartList = carts[cartKey] || null;

    this.setData({cartList: cartList})
    this.cartStat();
  },


  clearCart(e) { //清空
    this.setData({
      cartList: null,
      // cartDialog: false
    })
    this.cartStat();
  },

  dialogOpt(e) {
    const dialog_key = e.currentTarget.dataset.dk,
      type = e.currentTarget.dataset.type,
      csIdx = e.currentTarget.dataset.index,
      currentGoods = this.data.goods;

    if (type == 1) {
      this.setData({
        [dialog_key]: true,
        currentSpcIdx: csIdx
      })

      if (dialog_key == 'skuDialog') { //规格
        if (Util.isEmpty(currentGoods))
          return false;

        this.setData({
          current_cartKey: this.getCartKey(),
          goods: currentGoods,
          [dialog_key]: true,
        })

        let checkSkuTxt = [],
          skus = [],
          cartGoods = !Util.isEmpty(this.data.cartList) ? this.data.cartList['product_' + currentGoods.id] : null;

        this.setData({
          // skus: currentGoods.specs || [],
          // checkSkus: [],
          // checkSkuTxt: '',
          // checkSkuTxt: checkSkuTxt.length > 0 ? checkSkuTxt.join(',') : '',
          showSkuCartBtn: checkSkuTxt.length > 0 ? true : false,
          // totalPrice: currentGoods.price || 0
        })
      }
      return
    }

    this.setData({
      [dialog_key]: false
    })

    if (dialog_key == 'skuDialog') { //规格
      this.setData({
        skus: [],
        checkSkus: [],
        checkSkuTxt: '',
        totalPrice: 0,
      })
    }

  },

  optCart(e) { //计算购物车数量
    this.setData({
      cartList: e.detail || null
    })
    this.cartStat();
  },

  changeSku(e) { //选择 规格
    const index = e.currentTarget.dataset.index,
      sindex = e.currentTarget.dataset.sindex,
      cateIdx = this.data.curIndex,
      goodsIdx = this.data.currentSpcIdx;

    const product = this.data.goods;
    if (Util.isEmpty(product.specs) || Util.isEmpty(product.specs[index].items)) {
      return false;
    }

    product.specs[index].items.forEach((item, sidx) => {
      if (product.product_type == 1) {
        if (product.specs[index].amount == 1) {
          if (item.check && sidx != sindex) {
            item.check = false;
          }
        }

        if (sidx == sindex) {
          item.check = !item.check;
        }
      } else if (sidx === sindex) {
        item.check = !item.check;
      } else {
        if (!item.muti) {
          item.check = false;
          return;
        }
      }
    })

    //判断数量
    let select_amount = 0;
    product.specs[index].items.map(item => {
      if (item.check) {
        select_amount += 1;
      }
    })

    if (select_amount > product.specs[index].amount) {
      Util.Tips({
        title: product.specs[index].title + '最多选择' + categoryList[cateIdx].goodsList[goodsIdx].specs[index].amount + '份',
        hideMask: true
      })

      product.specs[index].items[sindex].check = false;
      return;
    }

    //检查是否显示按钮
    let showSkuCartBtn = true;
    product.specs.map(spec => {
      let sTotal = 0;
      spec.items.map(item => {
        if (item.check) {
          sTotal += 1
        }
      })

      if (sTotal < spec.amount) {
        showSkuCartBtn = false;
        return;
      }
    })

    this.setData({
      goods: product,
      showSkuCartBtn: showSkuCartBtn
    })

    let checkSkuTxt = [],
      checkSkus = [],
      totalPrice = parseFloat(product.price || 0);

    product.specs.forEach((spec, sidx) => {
      spec.items.map((item, idx) => {
        if (item.check === true) {
          checkSkus.push(item);
          checkSkuTxt.push(item.title);
          totalPrice += parseFloat(item.price || 0); // 计算价格
        }
      })
    })

    let cartList = this.data.cartList;
    if (!Util.isEmpty(cartList) && !Util.isEmpty(cartList['product_' + product.id])) {
      let carts = Util.getCartList() || {},
        cartKey = this.getCartKey();

      if (checkSkus.length > 0) {
        cartList['product_' + product.id].skus = checkSkus;
        cartList['product_' + product.id].skuTxt = checkSkuTxt.join(',');
        carts[this.getCartKey()] = cartList;
      } else {
        delete cartList['product_' + product.id];
        delete carts[cartKey]['product_' + product.id];
      }
      this.setData({
        cartList: cartList
      })
      if (Util.isEmpty(carts[cartKey])) {
        delete carts[cartKey];
      }
      wx.setStorageSync("carts", JSON.stringify(carts))
      this.cartStat();
    }

    this.setData({
      checkSkus: checkSkus,
      checkSkuTxt: checkSkuTxt.join(','),
      totalPrice: parseFloat(totalPrice).toFixed(1)
    })

  },

  _initSkuData() { //初始化规格数据
    const that = this;
    let skus = this.data.skus,
      checkSkuTxt = [],
      checkSkus = [];

    skus.forEach(sku => {
      sku.items.forEach((item, sidx) => {

        if (item.check === true) {
          checkSkuTxt.push(item.title)
          checkSkus.push(item)
        }

        if (item.price && item.check) {
          that.setData({
            totalPrice: item.price
          })
        }

      })
    })

    this.setData({
      checkSkus: checkSkus,
      checkSkuTxt: checkSkuTxt.join(','),
    })

  },

  addSkuCart(e) { //增加规格到购物车
    const that = this,
      sindex = e.currentTarget.dataset.sindex,
      cateIdx = this.data.curIndex,
      key = this.data.currentSpcIdx,
      current_menu = this.data.current_menu;

    if (Util.isEmpty(current_menu)) {
      return Util.Tips({title: "暂无菜单"})
    }

    if (current_menu.is_order == 2) {
      return Util.Tips({title: "暂不能预订"})
    } else if (current_menu.is_order == 0) {
      return Util.Tips({title: "已过预订时间"})
    }
    const checkSkus = that.data.checkSkus,
      type = parseInt(e.currentTarget.dataset.type);  // 1 : 增加  0： 减少

    let product = this.data.goods || null;
    if (Util.isEmpty(product))
      return;

    let cartList = Util.getCartList() || {}, amount = 0;
    const cartKey = this.getCartKey();

    let carts = {};
    if (!Util.isEmpty(cartList) && !Util.isEmpty(cartList[cartKey])) {
      carts = cartList[cartKey]
    }


    if (Util.isEmpty(carts) || Util.isEmpty(carts['product_' + product.id])) {//新增
      if (type === 1) {
        carts['product_' + product.id] = {
          title: product.title,
          id: product.id,
          limit_num: product.limit_num,
          bag_price: product.bag_price || 0,
          min_buy: product.min_buy || 0,
          amount: 0,
          product_type: product.product_type || 0,
          thumb: product.thumb,
          price: product.price || 0.00
        }
      }
    } else {
      amount = carts['product_' + product.id].amount;
    }

    if (type === 1) {
      amount += 1;
    } else {
      amount -= 1;
    }

    amount = amount <= 0 ? 0 : amount;
    if (amount === 0) {
      delete carts["product_" + product.id];
    } else {
      carts['product_' + product.id]['amount'] = amount;

      if (!Util.isEmpty(checkSkus)) {
        carts['product_' + product.id]['skus'] = checkSkus;

        let skuTxt = [],
          skuIds = [],
          totalPrice = parseFloat(product.price);

        checkSkus.map((e1) => {
          if (product.product_type == 1) {
            skuTxt.push(e1.title + ' x' + (e1.cart_amount || 1));
          } else {
            skuTxt.push(e1.title);
          }
          if (e1.price > 0) {
            totalPrice += parseFloat(e1.price);
          }
        })

        if (skuTxt.length > 0) {
          carts['product_' + product.id].skuTxt = skuTxt.join("、");
          carts['product_' + product.id].total_price = totalPrice.toFixed(1);
        }
      }
    }

    that.setData({
      cartList: carts,
      checkSkus: [],
      checkSkusTxt: "",
      // skuDialog: false
    })

    cartList[cartKey] = carts;
    that.cartStat();
    wx.setStorageSync("carts", JSON.stringify(cartList))
  },

  getCartKey() { //购物车key
    let cart_key = 'cartList' + this.data.shop_id
    if (!Util.isEmpty(this.data.current_menu)) {
      cart_key += '_' + (this.data.current_menu.id || 0)
    }
    return cart_key;
  },

  showCartDialog(e) {
    //购物车显示
    const carts = this.data.cartList;

    if (Util.isEmpty(carts)) {
      return false;
    }

    this.setData({
      cartDialog: true
    })
  },

  cartStat() {
    const carts = this.data.cartList;
    if (Util.isEmpty(carts)) {
      this.setData({
        buyActive: false,
        btnActive: false,
        cartTotal: {}
      })
      return;
    }

    let total_price = 0,
      total_amount = 0,
      shop = this.data.shop,
      bag_price = 0,
      buyActive = false;

    for (const k in carts) {
      total_price += (carts[k].total_price || carts[k].price || 0.0) * carts[k].amount
      total_amount += carts[k].amount;
      bag_price += (parseFloat(carts[k].bag_price) * (carts[k].amount || 1)) || 0;
    }

    let shipping_price = Util.getShopShippingPrice(total_amount, this.data.shop.base_shipping_price || null)
    total_price = (parseFloat(total_price) + parseFloat(shipping_price) + parseFloat(bag_price)).toFixed(1);
    buyActive = (Util.isEmpty(shop.min_money) || total_price >= shop.min_money) ? true : false;

    // 产品最低价格
    let total_product_price = (parseFloat(total_price) - parseFloat(shipping_price)).toFixed(2);
    if (total_product_price < shop.min_money) {
      buyActive = false;
    }
    this.setData({
      buyActive: buyActive,
      cartTotal: {
        shipping_price: shipping_price || 0,
        amount: total_amount,
        total_price: total_price,
        bag_price: bag_price,
        shop_min_money: shop.min_money || 0,
        total_product_price: total_product_price
      }
    })

  },

  cartOptCombo(e) {
    const that = this,
      key = e.currentTarget.dataset.key,
      type = parseInt(e.currentTarget.dataset.type);  // 1 : 增加  0： 减少

    const current_menu = this.data.current_menu;
    if (Util.isEmpty(current_menu)) {
      return app.Tips({title: "暂无菜单"})
    }

    if (current_menu.is_order == 2) {
      return app.Tips({title: "暂不能预订"})
    } else if (current_menu.is_order == 0) {
      return app.Tips({title: "已过预订时间"})
    }
    const product = this.data.goods || null;
    if (Util.isEmpty(product))
      return;

    let cartList = Util.getCartList() || {}, amount = 0;
    const cartKey = this.getCartKey();

    let carts = {};
    if (!Util.isEmpty(cartList) && !Util.isEmpty(cartList[cartKey])) {
      carts = cartList[cartKey]
    }

    if (Util.isEmpty(carts) || Util.isEmpty(carts['product_' + product.id])) {//新增
      if (type === 1) {
        carts['product_' + product.id] = {
          title: product.title,
          id: product.id,
          amount: 0,
          thumb: product.thumb,
          limit_num: product.limit_num,
          bag_price: product.bag_price || 0,
          product_type: product.product_type || 0,
          min_buy: product.min_buy || 0,
          price: product.price || 0.00
        }
      }
    } else {
      amount = carts['product_' + product.id].amount;
    }

    if (type === 1) {
      if (product.min_buy > 0 && (!Util.isEmpty(carts['product_' + product.id]) && carts['product_' + product.id].amount == 0)) {
        amount = product.min_buy;
      } else {
        amount += 1;
      }

      if (carts['product_' + product.id].limit_num > 0 && amount > carts['product_' + product.id].limit_num) {
        return Util.Tips({title: "限购数量" + carts['product_' + product.id].limit_num + '份', hideMask: true})
      }
      // amount += 1;
    } else {
      if (product.min_buy > 0 && product.min_buy >= amount) {
        amount -= product.min_buy || 0;
      } else {
        amount -= 1;
      }
    }
    amount = amount <= 0 ? 0 : amount;
    if (amount === 0) {
      delete carts["product_" + product.id];
    } else {
      carts['product_' + product.id]['amount'] = amount;
    }

    that.setData({cartList: carts})
    that.cartStat();
    cartList[cartKey] = carts;
    wx.setStorageSync("carts", JSON.stringify(cartList))
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  onLoadTabbar() {//底部tabbar返回数据
    const that = this
    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})
    }).then(() => {
      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          if (!rect) return;
          let bottom = rect.height + 10
          that.setData({
            bottom: bottom,
            cart_bottom: rect.height
          })
        }).exec()
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  }
  ,

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
  ,

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})